<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">任务清单</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<!-- card1 -->
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">预算清单</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form1" label-position="right" label-width="100px" :rules="rules.rules1" :model="formData.data">
							<el-form-item label="一级分类：" prop="level1">
								<el-select v-model="formData.data.level1" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="handleType == 'add' ? false : true" filterable @change="getClassificationDownFn('second', 'action')">
									<el-option v-for="item in classificationDown.first" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="二级分类：" prop="level2">
								<el-select v-model="formData.data.level2" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="handleType == 'add' ? false : true" filterable @change="getClassificationDownFn('third', 'action')">
									<el-option v-for="item in classificationDown.second" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="三级分类：" prop="level3">
								<el-select v-model="formData.data.level3" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="handleType == 'add' ? false : true" filterable @change="getClassificationDownFn('inventoryList', 'action')">
									<el-option v-for="item in classificationDown.third" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="清单名称：" prop="inventoryId">
								<el-select v-model="formData.data.inventoryId" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="handleType == 'add' ? false : true" filterable>
									<el-option v-for="item in classificationDown.inventoryList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-form>
					</div>
					<!-- card2 -->
					<div class="zs-align-center zs-space-top-lg zs-space-bottom" id="sm-drawer-demo-card-02">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">任务信息</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form2" label-position="right" label-width="100px" :rules="rules.rules2" :model="formData.data">
							<el-form-item label="任务名称：" prop="planName">
								<el-input v-model="formData.data.planName" :maxlength="50" :disabled="isReadOnly" />
							</el-form-item>
							<!-- <el-form-item label="选择流程：" prop="processKey">
								<el-select class="zs-full-item" v-model="formData.data.processKey" clearable filterable :disabled="isReadOnly">
									<el-option v-for="item in processList" :key="item.processKey" :label="item.optionName" :value="item.processKey" />
								</el-select>
							</el-form-item> -->
							<el-form-item label="选择角色：" prop="roleKey">
								<el-select class="zs-full-item" v-model="formData.data.roleKey" placeholder=" " filterable :disabled="isReadOnly">
									<el-option v-for="item in roleList" :key="item.role.roleKey" :label="item.role.name" :value="item.role.roleKey" />
								</el-select>
							</el-form-item>
							<el-form-item label="任务时长：" prop="maintenanceDuration">
								<div class="zs-layout-flex-row zs-layout-justify-between">
									<el-input class="date-num-input zs-space-right" v-model="formData.data.maintenanceDuration" :maxlength="10" :disabled="isReadOnly" />
									<el-select style="width: 50%" class="zs-full-item" v-model="formData.data.unitOfMaintenanceDuration" :disabled="isReadOnly">
										<el-option v-for="item in unitList" :key="item.id" :label="item.dicName" :value="item.id" />
									</el-select>
								</div>
							</el-form-item>
							<el-form-item label="说明：">
								<el-input v-model="formData.data.remark" :maxlength="curTextareaLength" show-word-limit type="textarea" :autosize="{ minRows: 2 }" :disabled="isReadOnly" />
							</el-form-item>
						</el-form>
					</div>
					<!-- card3 -->
					<EffectAndFailureTime ref="effectTimeRef" title="生效状态" id="sm-drawer-demo-card-03" :isReadOnly="isReadOnly" labelWidth="110px" />
					<!-- card4 -->
					<CreateUserInfo v-if="formData.data.id" ref="createDataRef" title="创建信息" id="sm-drawer-demo-card-04" />
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import EffectAndFailureTime from '@/components/effectAndFailureTime.vue';
	import CreateUserInfo from '@/components/createUserInfo.vue';
	import { planMaintainAddApi, planMaintainUpdateApi, planMaintainInfoApi, rolePlanListApi } from '@/api/facility.js';
	import { getInventoryApi, processTypeListApi, roleListApi } from '@/api/common.js';
	import { ElMessage } from 'element-plus';
	import { ref, reactive, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';

	const route = useRoute();

	const unitList = [
		{ id: 3, dicName: '分钟' },
		{ id: 0, dicName: '小时' },
		{ id: 1, dicName: '天' },
	];

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
	});

	let store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSize);
	const curTextareaLength = ref(store.state.uiTextareaLength);

	const emit = defineEmits(['close']);

	let isShowDrawer = ref(props.isShow);

	let formData = reactive({ data: {unitOfMaintenanceDuration: 1} });

	const rules = reactive({
		rules1: {
			level1: [{ required: true, message: '请选择一级分类', trigger: 'change' }],
			level2: [{ required: true, message: '请选择二级分类', trigger: 'change' }],
			level3: [{ required: true, message: '请选择三级分类', trigger: 'change' }],
			inventoryId: [{ required: true, message: '请选择清单名称', trigger: 'change' }],
		},
		rules2: {
			planName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
			// processKey: [{ required: true, message: '请选择流程', trigger: 'change' }],
			roleKey: [{ required: true, message: '请选择角色', trigger: 'change' }],
			maintenanceDuration: [{ required: true, message: '请选择任务时长', trigger: 'change' }],
		},
	});

	const curNodeList = ref([
		{ name: '预算清单', id: 'sm-drawer-demo-card-01' },
		{ name: '任务信息', id: 'sm-drawer-demo-card-02' },
		{ name: '生效状态', id: 'sm-drawer-demo-card-03' },
	]);

	const form1 = ref();
	const form2 = ref();
	const forms = [form1, form2];
	let effectTimeRef = ref();
	let createDataRef = ref();

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && props.handleType == 'add' && initForm();
				newVal && ['info', 'edit'].includes(props.handleType) && getInfo(props.currentRow?.id);
			});
		},
	);

	// 三级分类
	let classificationDown = reactive({
		first: [],
		second: [],
		third: [],
		inventoryList: [],
	});

	//三级分类 | 清单名称
	const getClassificationDownFn = async (type = 'first', action) => {
		let params = {};
		if (type == 'second' && action == 'action') {
			initAffectFiled('level2', 'second');
			initAffectFiled('level3', 'third');
			initAffectFiled('inventoryId', 'inventoryList');
		} else if (type == 'third' && action == 'action') {
			initAffectFiled('level3', 'third');
			initAffectFiled('inventoryId', 'inventoryList');
		} else if (type == 'inventoryList' && action == 'action') {
			initAffectFiled('inventoryId', 'inventoryList');
		}
		setTimeout(function () {
			action == 'action' && clearClassValidate();
		}, 30);

		params.classify1 = ['inventoryList', 'third', 'second'].includes(type) ? formData.data.level1 : '';
		params.classify2 = ['inventoryList', 'third'].includes(type) ? formData.data.level2 : '';
		params.classify3 = ['inventoryList'].includes(type) ? formData.data.level3 : '';

		let res = await getInventoryApi(params);
		let resData = res.data;
		if (resData.code == 200) {
			classificationDown[type] = resData.data;
		}
	};

	//级联选择变化时清空下选的被动项
	const initAffectFiled = (fieldName, listName) => {
		formData.data[fieldName] = '';
		classificationDown[listName] = [];
	};
	const clearClassValidate = () => {
		form1.value.clearValidate('level2');
		form1.value.clearValidate('level3');
		form1.value.clearValidate('inventoryId');
	};

	//详情
	const getInfo = async id => {
		let res = await planMaintainInfoApi(id);
		if (res.data.code !== 200) return;
		let existCreate = curNodeList.value.find(item => item.id === 'sm-drawer-demo-card-04');
		!existCreate && curNodeList.value.push({ name: '创建信息', id: 'sm-drawer-demo-card-04' });
		let cData = Object.assign(res.data.data);
		handleDataType(cData);
		formData.data = cData;
		effectTimeRef.value.setTime({ effectTime: formData.data.startTime, expireTime: formData.data.endTime });
		// 分类数据源
		getClassificationDownFn('second');
		getClassificationDownFn('third');
		getClassificationDownFn('inventoryList');
		nextTick(() => {
			createDataRef.value.setData(formData.data);
		});
	};

	const handleDataType = data => {
		data.level1 = Number(data.level1);
		data.level2 = Number(data.level2);
		data.level3 = Number(data.level3);
	};

	//提交
	const doConfirm = async () => {
		const validatePromises = forms.map(form => new Promise(resolve => form.value.validate(resolve)));
		const timeModel = effectTimeRef.value.checkRequired();
		validatePromises.push(timeModel)

		Promise.all(validatePromises).then(async results => {
			const isValid = results.every(valid => valid);
			if (!isValid) return;
			let params = Object.assign(formData.data, effectTimeRef.value.getFiled());
			params.projectCode = route.query.projectCode;
			params.inventoryName = classificationDown.inventoryList.find(item => item.id == params.inventoryId)?.name;

			let res = formData.data.id ? await planMaintainUpdateApi(params) : await planMaintainAddApi(params);
			if (res.data.code == 200) {
				ElMessage({
					message: '提交成功',
					type: 'success',
				});
				isShowDrawer.value = false;
				emit('close', { isShow: false, isRefresh: true });
			}
		});
	};

	//流程列表
	// let processList = ref([]);
	// const getProcessList = async () => {
	// 	let res = await processTypeListApi(2);
	// 	if (res.data.data && res.data.data) {
	// 		res.data.data.forEach(item => {
	// 			item.optionName = `${item.name}（${item.processKey}）`;
	// 		});
	// 		processList.value = res.data.data || [];
	// 	}
	// };

	//角色列表
	let roleList = ref([]);
	const getRoleList = async () => {
		let res = await rolePlanListApi();
		roleList.value = res.data.data || [];
	};

	//关闭抽屉
	const handleClose = done => {
		effectTimeRef.value.restTime();
		emit('close', { isShow: false });
		done();
	};

	//表单初始化
	const initForm = () => {
		formData.data = {unitOfMaintenanceDuration:1};
		effectTimeRef.value.setTime({});
		forms.forEach(form => {
			form.value.resetFields();
		});
		let existCreate = curNodeList.value.find(item => item.id === 'sm-drawer-demo-card-04');
		existCreate && curNodeList.value.pop();
	};

	getClassificationDownFn('first', '');
	getRoleList();
</script>
